package com.cc.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Encoder;

public class Cifrado {

	private static String semilla = "7657CONSU7T0R1467CC87";
	
	public static String cifrar(final String textoClaro){
		try{
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, generarLlave());
			byte[] claveEncriptadaBytes = cipher.doFinal( textoClaro.getBytes() );
			return new BASE64Encoder().encode( claveEncriptadaBytes );
		}catch (Exception e) {
			return "";
		}
	}

	public static String descifrar(final String textoCifrado){
		try{
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, generarLlave());
	
			byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(textoCifrado);
			byte[] utf8 = cipher.doFinal(dec); // Decode using utf-8
			return new String(utf8, "UTF8");
		}catch (Exception e) {
			return "";
		}
		
	}
	private static SecretKeySpec generarLlave(){
		return new SecretKeySpec(new String((semilla.trim()).substring(0, 8)).getBytes(), "DES");
	}


	public static void main(final String[] args) throws Exception {
		String pass = Cifrado.cifrar("consultores");
		System.out.println("cifrado: " + pass);
		String claro = Cifrado.descifrar("+k82zy4HcoeNw75qEn7oEQ==");
		System.out.println("descifrado: " + claro);
	}

}
